/*

Copyright (c) 2008, Dependable Systems Lab, EPFL
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, 
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.
    * Neither the name of the Dependable Systems Lab, EPFL nor the names of its 
      contributors may be used to endorse or promote products derived from this 
      software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR 
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON 
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

package conferr.gui;

import conferr.*;
import conferr.gui.MainFrame;
import conferr.gui.JDisablingPanel;
import conferr.ClassFinderBean;
import java.awt.Dimension;
import java.awt.Font;
import java.io.StringWriter;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.table.TableColumn;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdom.Document;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

/**
 *
 * @author  lokeller
 */
public class ConfigurationFiltersFrame extends javax.swing.JFrame {
    
    /** Creates new form ConfigurationFiltersFrame */
    public ConfigurationFiltersFrame(FaultInjectionPlan plan, ErrorGenerator sset) {
        
        this.plan = plan;
        this.scenarioSet = sset;
        initComponents();
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        plan = plan;
        filterBean = new conferr.gui.ConfigurationFilterBean();
        scenarioSet = scenarioSet;
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jPanel1 = new JDisablingPanel();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        filterParamTable = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jPanel2 = new JDisablingPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Edit filters");
        getContentPane().setLayout(new java.awt.GridBagLayout());

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${configurationFiles}");
        org.jdesktop.swingbinding.JListBinding jListBinding = org.jdesktop.swingbinding.SwingBindings.createJListBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, plan, eLProperty, jList1);
        jListBinding.setDetailBinding(org.jdesktop.beansbinding.ELProperty.create("${name}"));
        bindingGroup.addBinding(jListBinding);

        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jList1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        getContentPane().add(jButton1, gridBagConstraints);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jList1, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), jPanel1, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jPanel1.setLayout(new java.awt.GridBagLayout());

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, filterBean, org.jdesktop.beansbinding.ELProperty.create("${filter.pluginClass}"), jTextField1, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jTextField1, gridBagConstraints);

        jLabel1.setText("Transform:");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jLabel1, gridBagConstraints);

        filterParamTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Name", "Value"
            }
        ));
        filterParamTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                filterParamTablePropertyChange(evt);
            }
        });
        {
            eLProperty = org.jdesktop.beansbinding.ELProperty.create("${filter.params}");
            org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, filterBean, eLProperty, filterParamTable);
            bindingGroup.addBinding(jTableBinding);
            BeanProperty nameP = BeanProperty.create("name");
            BeanProperty typeP = BeanProperty.create("type");
            BeanProperty valueP = BeanProperty.create("value");
            jTableBinding.addColumnBinding(nameP).setColumnName("Name").setEditable(false);
            jTableBinding.addColumnBinding(typeP).setColumnName("Type").setEditable(false);
            jTableBinding.addColumnBinding(valueP).setColumnName("Value");
            jTableBinding.bind();
        }
        jScrollPane3.setViewportView(filterParamTable);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jScrollPane3, gridBagConstraints);

        jButton4.setText("...");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jButton4, gridBagConstraints);

        jButton2.setText("View after transform...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jButton3.setText("View after inverse transform...");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton3);

        jButton5.setText("View serialized...");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton5);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 5, 5);
        jPanel1.add(jPanel2, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jPanel1, gridBagConstraints);

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
        
        if (jList1.getSelectedValue() != null)
            filterBean.setFilter(scenarioSet.getConfigurationTransform(plan.getConfigurationFiles().get(jList1.getSelectedIndex())));
        
    }//GEN-LAST:event_jList1ValueChanged

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        ClassFinderBean cfbean = new ClassFinderBean(plan);
        
        cfbean.setInterfaceName("conferr.Transform");
        
        Vector<String> classes = cfbean.getClassesNames();
        
        String[] classesA = classes.toArray(new String[classes.size()]);
        
        String selectedValue = (String) JOptionPane.showInputDialog(this, "Choose transform", "Filter",
                JOptionPane.INFORMATION_MESSAGE, null,
                classesA, classesA[0]);
        if (selectedValue != null) 
            filterBean.getFilter().setPluginClass(selectedValue);

    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        ConfigurationFile file = plan.getConfigurationFiles().get(jList1.getSelectedIndex());
        
        if (file.getPluginClass() == null || file.getPluginClass().equals("")) {
            JOptionPane.showMessageDialog(this, "Please select an handler for the file");
            return;
        }
        
        if (filterBean.getFilter().getTransformInstance() == null ) {
            JOptionPane.showMessageDialog(this, "Please select a valid transform");
            return;
        }
        
        try {
                        
            Document doc = filterBean.getFilter().getTransformInstance().filter(file.getDocument(), filterBean.getFilter());                      
            
            XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
            
            StringWriter wout = new StringWriter();
            
            out.output(doc, wout);
            
            JTextArea area = new JTextArea(wout.getBuffer().toString());
            area.setFont(new Font(Font.MONOSPACED, Font.PLAIN,12));
            JScrollPane pane = new JScrollPane(area);
            pane.setPreferredSize(new Dimension(900,500));
            
            JOptionPane.showMessageDialog(this, pane, "Filtered file", JOptionPane.PLAIN_MESSAGE);
            
            wout.close();
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);            
            JOptionPane.showMessageDialog(this, "Unable to filter file: " + ex.getMessage());
        }
        
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        ConfigurationFile file = plan.getConfigurationFiles().get(jList1.getSelectedIndex());
        
        if (file.getPluginClass() == null || file.getPluginClass().equals("")) {
            JOptionPane.showMessageDialog(this, "Please select an handler for the file");
            return;
        }
        
        if (filterBean.getFilter().getTransformInstance() == null ) {
            JOptionPane.showMessageDialog(this, "Please select a valid filter");
            return;
        }
        
        try {
                        
            
            Transform f = filterBean.getFilter().getTransformInstance();
            Document doc = f.unfilter(f.filter(file.getDocument(),filterBean.getFilter()), filterBean.getFilter());                      
            
            XMLOutputter out = new XMLOutputter(Format.getPrettyFormat());
            
            StringWriter wout = new StringWriter();
            
            out.output(doc, wout);
            
            JTextArea area = new JTextArea(wout.getBuffer().toString());
            area.setFont(new Font(Font.MONOSPACED, Font.PLAIN,12));
            JScrollPane pane = new JScrollPane(area);
            pane.setPreferredSize(new Dimension(900,500));
            
            JOptionPane.showMessageDialog(this, pane, "Filtered file", JOptionPane.PLAIN_MESSAGE);
            
            wout.close();
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);            
            JOptionPane.showMessageDialog(this, "Unable to filter file: " + ex.getMessage());
        }

    }//GEN-LAST:event_jButton3ActionPerformed

    private void filterParamTablePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_filterParamTablePropertyChange
        if (evt.getPropertyName().equals("model")) {
            TableColumn col = filterParamTable.getColumnModel().getColumn(2);
            col.setCellEditor(new ParameterCellEditor(plan,this, null));
        }
    }//GEN-LAST:event_filterParamTablePropertyChange

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        
        ConfigurationFile file = plan.getConfigurationFiles().get(jList1.getSelectedIndex());
        
        if (file.getPluginClass() == null || file.getPluginClass().equals("")) {
            JOptionPane.showMessageDialog(this, "Please select an handler for the file");
            return;
        }
        
        if (filterBean.getFilter().getTransformInstance() == null ) {
            JOptionPane.showMessageDialog(this, "Please select a valid filter");
            return;
        }
        
        try {
                        
            
            Transform f = filterBean.getFilter().getTransformInstance();
            Document doc = f.unfilter(f.filter(file.getDocument(),filterBean.getFilter()), filterBean.getFilter());                      
            
            StringWriter wout = new StringWriter();
            
            file.getHandlerInstance().serializeConfiguration(doc, wout, file);
            
            JTextArea area = new JTextArea(wout.getBuffer().toString());
            area.setFont(new Font(Font.MONOSPACED, Font.PLAIN,12));
            JScrollPane pane = new JScrollPane(area);
            pane.setPreferredSize(new Dimension(900,500));
            
            JOptionPane.showMessageDialog(this, pane, "Serialized file", JOptionPane.PLAIN_MESSAGE);
            
            wout.close();
        } catch (Exception ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);            
            JOptionPane.showMessageDialog(this, "Unable to filter file: " + ex.getMessage());
        }

    }//GEN-LAST:event_jButton5ActionPerformed
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private conferr.gui.ConfigurationFilterBean filterBean;
    private javax.swing.JTable filterParamTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField jTextField1;
    private conferr.FaultInjectionPlan plan;
    private conferr.ErrorGenerator scenarioSet;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    
}
